package com.chsi.onjava8.stream;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Enumeration;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @Auther shikf
 * @Date 2020-06-23 18:08
 */
public class FileToWordsRegexp {
    private String all;

    public FileToWordsRegexp(String filePath) throws Exception {
        all = Files.lines(Paths.get(filePath))
                .skip(1) // First (comment) line
                .collect(Collectors.joining(" "));
    }

    public Stream<String> stream() {
        return Pattern
                .compile("[ .,?]+").splitAsStream(all);
    }

    public static void
    main(String[] args) throws Exception {
        InputStream resourceAsStream = FileToWordsRegexp.class.getClassLoader().getResourceAsStream("Cheese.dat");
        File test_ = File.createTempFile("test_", ".data");
        FileUtils.copyInputStreamToFile(resourceAsStream,test_);
        System.out.println(test_.getAbsolutePath());
        FileToWordsRegexp fw = new FileToWordsRegexp(test_.getAbsolutePath());
        fw.stream()
                .limit(7)
                .map(w -> w + " ")
                .forEach(System.out::print);
        fw.stream()
                .skip(7)
                .limit(2)
                .map(w -> w + " ")
                .forEach(System.out::print);
    }
}
